﻿// ***********************************************************************
// Assembly         : CommonLayer
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
//
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="_LayoutViewControllers_Base.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.CommonLayer.Models;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.DomainLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.Extensions;
using INNOVACALL.Framework.Common.Models.ViewModels.LayoutViewModels;
using INNOVACALL.Framework.Common.Models.ViewModels.MetaModels;
using INNOVACALL.Framework.Common.MVCHelpers;
using INNOVACALL.Framework.Common.MVCHelpers.Localization;

namespace InnovaApp.Layers.CommonLayer.Controllers.ViewControllers.LayoutViewControllers
{
    /// <summary>
    /// Controler base de common layer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class _LayoutViewControllers_Base<T> : INNOVACALL.Framework.Common.Controllers.ViewControllers.LyoutViewControllers._LayoutViewControllers_Base<T> where T : INNOVACALL.Framework.Common.Models.ViewModels.LayoutViewModels._LayoutViewModels_Base
    {
        /// <summary>
        /// The _current user
        /// </summary>
        private MembershipUser _currentUser = null;
        /// <summary>
        /// The e method base
        /// </summary>
        private string eMethodBase = "InnovaApp.Layers.CommonLayer.Controllers_Controllers_Base<T>";

        /// <summary>
        /// The default language
        /// </summary>
        protected string DefaultLanguage = InnovaApp.Layers.CommonLayer.Controllers.CommonEnvironment.DefaultLanguage;

        #region  Variables membres
        /// <summary>
        /// The _content data
        /// </summary>
        private T _contentData;
        #endregion
        /// <summary>
        /// The j queryvalues
        /// </summary>
        private List<string> jQueryvalues = new List<string>();
        /// <summary>
        /// The j querycssvalues
        /// </summary>
        private List<string> jQuerycssvalues = new List<string>();

        /// <summary>
        /// The lien config
        /// </summary>
        private string lienConfig = "";
        /// <summary>
        /// Gets or sets the content data.
        /// </summary>
        /// <value>The content data.</value>
        public T ContentData
        {
            get
            {
                return _contentData;
            }
            set
            {
                _contentData = value;
            }
        }
        /// <summary>
        /// Return site base url for emails
        /// </summary>
        /// <value>The site base URL.</value>
        protected string SiteBaseURL
        {
            get
            {
                string toReturn = string.Empty;
                toReturn = InnovaApp.Layers.CommonLayer.Controllers.CommonEnvironment.SiteBaseUrl;
                if (toReturn.Substring(toReturn.Length - 1, 1) != "/")
                {
                    toReturn += "/";
                }
                toReturn += base.URLReferLanguage;
                return toReturn;
            }
        }

        #region Private members

        /// <summary>
        /// The _data context
        /// </summary>
        private DataRepositories _dataContext = null;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="_LayoutViewControllers_Base{T}"/> class.
        /// </summary>
        public _LayoutViewControllers_Base() : base() { }

        /// <summary>
        /// Initilializations the view (Framework Step 1).
        /// </summary>
        /// <param name="pageTitle">The page title.</param>
        /// <param name="openingMessage">The opening message.</param>
        /// <param name="specificCssCollection">The specific CSS collection.</param>
        /// <param name="specificJSCollection">The specific JS collection.</param>
        /// <param name="dynamicJSCollection">The dynamic JS collection.</param>
        /// <param name="specificJqueryJSCollection">The specific jquery JS collection.</param>
        /// <param name="jsVariables">The js variables.</param>
        /// <param name="externalCss">The external CSS.</param>
        /// <param name="metaToAdd">The meta to add.</param>
        /// <param name="_dataContext">The _data context.</param>
        /// <param name="displayMenus">if set to <c>true</c> [display menus].</param>
        /// <param name="language">The language.</param>
        /// <param name="adminMode">if set to <c>true</c> [admin mode].</param>
        /// <param name="usesKendoUI">if set to <c>true</c> [uses kendo UI].</param>
        /// <param name="jQueryUITheme">The j query UI theme.</param>
        /// <param name="kendoUITheme">The kendo UI theme.</param>
        /// <param name="currentUser">The current user.</param>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException"></exception>
        protected void InitView_Common(
            string pageTitle,
            string openingMessage,
            string[] specificCssCollection,
            string[] specificJSCollection,
            string[] dynamicJSCollection,
            string[] specificJqueryJSCollection,
            string[] jsVariables,
            string[] externalJs,
            string[] externalCss,
            Dictionary<enMeta, string> metaToAdd,
            DataRepositories _dataContext,
            bool displayMenus,
            string language,
            bool adminMode,
            bool usesKendoUI,
            string jQueryUITheme,
            string kendoUITheme,
            MembershipUser currentUser
        )
        {
            string eMethod = eMethodBase + ".InitView";
            object eParameters = new
            {
                pageTitle = pageTitle,
                openingMessage = openingMessage,
                specificCssCollection = specificCssCollection,
                specificJSCollection = specificJSCollection,
                dynamicJSCollection = dynamicJSCollection,
                specificJqueryJSCollection = specificJqueryJSCollection,
                jsVariables = jsVariables,
                externalCss = externalCss,
                metaToAdd = metaToAdd,
                _dataContext = _dataContext,
                displayMenus = displayMenus,
                language = language,
                adminMode = adminMode,
                usesKendoUI = usesKendoUI

            };
            Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == language).FirstOrDefault();
            if (dbLanguage == null)
            {
                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.Err_LanguageNotFound);
            }
            this.ContentData = base.ContentData;
            var contentData = this.ContentData as _LayoutViewModels_Base;
            string defaultLanguage = CommonEnvironment.DefaultLanguage;
            contentData._Languages = new Languages_MetaModel(dbLanguage.Description);
            contentData._AdminMode = adminMode;

            LayoutViewControllersStaticTools.FeedMenus(
                contentData._Menus, 
                _dataContext, 
                dbLanguage, 
                defaultLanguage, 
                adminMode, 
            currentUser);

            //Initialize view in Framework
            base.InitView_Framework(
                pageTitle, 
                openingMessage, 
                specificCssCollection, 
                specificJSCollection, 
                dynamicJSCollection, 
                specificJqueryJSCollection, 
                jsVariables, 
                externalJs, 
                externalCss, 
                displayMenus, 
                metaToAdd, 
                usesKendoUI, 
                jQueryUITheme, 
                kendoUITheme
            );
        }

        /// <summary>
        /// Libère des ressources non managées et, le cas échéant, des ressources managées.
        /// </summary>
        /// <param name="disposing">true pour libérer à la fois les ressources managées et non managées ; false pour ne libérer que les ressources non managées.</param>
        protected override void Dispose(bool disposing)
        {
            if (_dataContext != null)
            {
                _dataContext.Dispose();
            }
            base.Dispose(disposing);
        }
        /// <summary>
        /// Gets the language with friendly URL.
        /// </summary>
        /// <param name="friendlyUrl">The friendly URL.</param>
        /// <returns>System.Int32.</returns>
        protected int GetLanguageWithFriendlyURL(string friendlyUrl)
        {
            string DefaultLanguage = InnovaApp.Layers.CommonLayer.Controllers.CommonEnvironment.DefaultLanguage;
            int toReturn = -1;
            if (friendlyUrl == "/")
            {
                friendlyUrl = "/" + DefaultLanguage;
            }
            string culture = friendlyUrl.Substring(1, 5);
            toReturn = EnumTools.EnumTypeTo<int>(culture.Substring(0, 2));
            return toReturn;
        }
        /// <summary>
        /// Singleton : Identified User
        /// </summary>
        /// <value>The current user.</value>
        protected MembershipUser CurrentUser
        {
            get
            {
                if (_currentUser == null)
                {
                    _currentUser = Membership.GetUser();
                }
                return _currentUser;
            }
        }

        /// <summary>
        /// Contents the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="contentEncoding">The content encoding.</param>
        /// <returns>ContentResult.</returns>
        protected override ContentResult Content(string content, string contentType, System.Text.Encoding contentEncoding)
        {
            return base.Content(content.Replace("\t", string.Empty), contentType, contentEncoding);
        }

        /// <summary>
        /// Prepares a landing page path for a specified user
        /// </summary>
        /// <param name="landingPage">The landing page.</param>
        /// <param name="language">The language.</param>
        /// <param name="userEMail">The user E mail.</param>
        /// <param name="userCreationDate">The user creation date.</param>
        /// <returns>System.String.</returns>
        protected string SendMailSecurizedLandingPageBuilder(InnovaApp.Layers.CommonLayer.enLandingPages landingPage, string language, string userEMail, string userCreationDate)
        {
            string toReturn = string.Empty;
            object eMethodParameters = new { @landingPage = landingPage, @language = language, @userEMail = userEMail, @userCreationDate = userCreationDate };
            string landingPageAddress = string.Format(@"http://{0}", this.SiteBaseURL);
            string cryptedPart = string.Format("{0}{1}", userEMail, string.Format("{0:dd/MM/yyyy hh:mm:ss}", userCreationDate));
            cryptedPart = cryptedPart.EncodeSHA1();
            landingPageAddress = string.Format(@"{0}/{1}?activationcode={2}&email={3}", landingPageAddress, StringEnum.GetStringValue(landingPage), Server.UrlEncode(cryptedPart), Server.UrlEncode(userEMail));
            toReturn = landingPageAddress;
            return toReturn;
        }

        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="toDisplayName">To display name.</param>
        /// <param name="messageSubject">The message subject.</param>
        /// <param name="isBodyHtml">if set to <c>true</c> [is body HTML].</param>
        /// <param name="messageBody">The message body.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.CommonException"></exception>
        protected bool SendMail(string from, string to, string toDisplayName, string messageSubject, bool isBodyHtml, string messageBody)
        {
            bool toReturn = true;
            MailAddress From;
            object eMethodParameters = new { @from = from, @to = to, @subject = messageSubject, @messageBody = messageBody };
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Request.ApplicationPath);
            MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            try
            {
                if (string.IsNullOrEmpty(from))
                {
                    From = new MailAddress(ConfigurationManager.AppSettings["AccountActivationFromMailAddress"], this.SiteBaseURL);
                }
                else
                {
                    From = new MailAddress(from);
                }
                MailAddress To = new MailAddress(to, toDisplayName);

                MailMessage Message = new MailMessage(From, To);
                Message.IsBodyHtml = isBodyHtml;
                Message.Subject = messageSubject;
                Message.Body = messageBody;

                SmtpClient smtp = new SmtpClient();
                smtp.UseDefaultCredentials = settings.Smtp.Network.DefaultCredentials;
                smtp.Host = settings.Smtp.Network.Host;
                smtp.Port = settings.Smtp.Network.Port;
                smtp.EnableSsl = settings.Smtp.Network.EnableSsl;
                smtp.Credentials = new NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);
                smtp.Send(Message);
            }
            catch (Exception ex)
            {
                string errorMessage = "The folowing error occurs : \n";
                errorMessage += ex.Message;
                toReturn = false;
                return toReturn;
                throw new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethodBase + "SendMail", eMethodParameters, errorMessage);
            }

            return toReturn;
        }
        /// <summary>
        /// Returns true if CurrentUser is not null and if he is in Admin role
        /// </summary>
        /// <value><c>true</c> if [admin mode]; otherwise, <c>false</c>.</value>
        protected bool AdminMode
        {
            get
            {
                bool toReturn = false;
                if (this.CurrentUser != null)
                {
                    toReturn = Roles.IsUserInRole(this.CurrentUser.UserName, "Admin") || Roles.IsUserInRole(this.CurrentUser.UserName, "Writer");
                }
                return toReturn;
            }
        }
        /// <summary>
        /// Gets the language description with friendly URL.
        /// </summary>
        /// <param name="friendlyUrl">The friendly URL.</param>
        /// <returns>System.String.</returns>
        protected string GetLanguageDescriptionWithFriendlyURL(string friendlyUrl)
        {
            string toReturn = InnovaApp.Layers.CommonLayer.Controllers.CommonEnvironment.DefaultLanguage;
            if (friendlyUrl != "/")
            {
                toReturn = friendlyUrl.Substring(1, 5);
            }
            return toReturn;
        }
        /// <summary>
        /// Localizes the dynamic script.
        /// </summary>
        /// <param name="language">The language.</param>
        protected void LocalizeDynamicScript(string language,string userLanguage)
        {
            if (!string.IsNullOrEmpty(userLanguage))
            {
                language = userLanguage;
            }
            INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.SetCurrentThreadLanguage(language);
            for (var i = 0; i < base.dynamicJSCollection.Length; i++)
            {
                base.dynamicJSCollection[i] = base.dynamicJSCollection[i].Replace("/ScriptsG/", string.Format("/ScriptsG/{0}/", language));
            }
        }
    }
}
